package com.zhanghe.study.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * 服务端
 * @author zh
 * @date 2020/12/2 11:33
 */
public class Server {
    public static void main(String[] args) throws InterruptedException {
        // bossGroup用于接收Client端连接
        // NioEventLoopGroup中的子线程数默认是cpu核数*2
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        // workerGroup用于实际业务处理的
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try{
            // 辅助类  对server进行一系列的配置
            ServerBootstrap bootstrap = new ServerBootstrap();
            // 将两个工作线程组加入进来
            bootstrap.group(bossGroup,workerGroup)
                    // 指定NioServerSocketChannel类型的通道
                    .channel(NioServerSocketChannel.class)
                    // 使用childHandler绑定具体的事件处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // 管道中加入处理器
                            socketChannel.pipeline().addLast(new ServerHandler());
                        }
                    })
                    // tcp缓冲区,线程队列等待连接的个数
                    .option(ChannelOption.SO_BACKLOG,128)
                    // 保持活动连接状态
                    .childOption(ChannelOption.SO_KEEPALIVE,true);

            System.out.println("服务器启动");
            // 绑定端口并同步
            ChannelFuture future = bootstrap.bind(8765).sync();
            // 阻塞  防止关闭  只有关闭事件触发才会执行
            future.channel().closeFuture().sync();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }
}
